package com.kantboot.system.user.user.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import com.kantboot.system.user.user.domain.entity.SysUserToken;
import com.kantboot.system.user.user.dao.repository.SysUserTokenRepository;
import com.kantboot.system.user.user.service.ISysUserTokenService;
import com.kantboot.util.core.redis.RedisUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SysUserTokenServiceImpl implements ISysUserTokenService {

    @Resource
    private SysUserTokenRepository repository;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public String generateToken(Long userId) {
        // 获取当前时间戳
        Long currentTimeMillis = System.currentTimeMillis();
        // 获取配置的token过期时间
        Long tokenExpireTime = 1000 * 60 * 60 * 24 * 7L;

        // token
        String token = IdUtil.simpleUUID() + MD5.create().digestHex(userId+"");
        SysUserToken sysToken = new SysUserToken()
                .setToken(token)
                .setUserId(userId)
                .setGmtExpire(new Date(currentTimeMillis + tokenExpireTime));

        // 保存token
        SysUserToken save = repository.save(sysToken);
        redisUtil.setEx("token:" + token, userId+"", tokenExpireTime);

        return save.getToken();
    }

}
